package com.ymtms.customerservice.service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ymtms.customerservice.dao.CallbackInformationMapper;
import com.ymtms.customerservice.dao.CollectionCallBackMapper;
import com.ymtms.customerservice.pojo.CallbackInformation;
import com.ymtms.customerservice.pojo.CollectingMoneyBalance;
import com.ymtms.customerservice.service.CollectionCallBackService;
import com.ymtms.customerservice.util.Smsutil;
import com.ymtms.customerservice.vo.GridRequest;
import com.ymtms.customerservice.vo.GridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CollectionCallBackServiceImpl implements CollectionCallBackService {
    @Autowired
    CollectionCallBackMapper collectionCallBackMapper;
    @Autowired
    CallbackInformationMapper callbackInformationMapper;

    @Override
    public GridResult<CollectingMoneyBalance> selectCollectionNewCallback(
            GridRequest gridRequest, CollectingMoneyBalance collectingMoneyBalance,
            String startTime, String endTime) {

        // 获取当前页和页大小
        Integer currentPage = gridRequest.getPage();
        Integer pageSize = gridRequest.getLimit();

        // 判断是否有排序,有则生成符合pagehelper的排序字符串
        String sidx = gridRequest.getSidx(); // 排序参数
        String sord = gridRequest.getSord(); // 排序规则

        String orderBy = "";
        // pagehelper静态设置页属性方法，它会拦截下面的第一个查询！第二个无效。
        if(checkOrderBy(sidx, sord)){
            sidx = upperCharToUnderLine(sidx);
            orderBy = sidx+" "+sord;

            PageHelper.startPage(currentPage, pageSize, orderBy);
        }else{
            // 设置当前页和页大小
            PageHelper.startPage(currentPage, pageSize);
        }

        // 查询结果（传入排序）
        List<CollectingMoneyBalance> result = collectionCallBackMapper.selectCollectionNewBill(collectingMoneyBalance, startTime, endTime);
        // 利用当前页和页大小配置pageinfo
        PageInfo<CollectingMoneyBalance> pageList = new PageInfo<>(result);
        // 新建一个封装类对象，设置参数，传入查询得到的数据
        GridResult<CollectingMoneyBalance> grid = new GridResult<>();

        // 存入查询数据
        grid.setData(result);
        // 存入总条数
        grid.setCount(pageList.getTotal());

        return grid;
    }

    @Override
    public CollectingMoneyBalance queryByGmid(Integer gmid) {
        CollectingMoneyBalance result = collectionCallBackMapper.selectByGmid(gmid);
        return result;
    }

    @Override
    public void executeCallback(Integer cmsid) {
        // 查询信息
        CollectingMoneyBalance collectingMoneyBalance = collectionCallBackMapper.selectByCmsid(cmsid);
        if(collectingMoneyBalance==null){
            throw new RuntimeException("未找到对应数据，请刷新页面");
        }
        // 先执行短信回告，异常则终止。
        // AccessKey ID
        String smsAppKey = "LTAI4FvkfMvefuXTFox1KYyN";
        // AccessKeySecret
        String smsSerect = "vkp9SLOoImHW0O1G5tx68jDvHfaQse";
        // 签名名称
        String smsSign = "运蒙";
        // 模板Id
        String smsModelId = "SMS_176910897";
        // 模板电话号码
//        String phone = collectingMoneyBalance.getGoodsbillMaster().getSendGoodsCustomerTel();
        String phone = "18982094200";
        // 模板参数
        JSONObject modelParam = new JSONObject();
        // 验证码
        int code = (int)(1000000*Math.random());
        modelParam.put("code",code);
        // 执行并返回参数
        boolean re = Smsutil.sendSms(smsAppKey, smsSerect, smsSign, smsModelId, phone, modelParam);
        if(re){
            throw new RuntimeException("短信发送失败，请重新发送");
        }

        // 传入信息
        CallbackInformation callbackInformation = new CallbackInformation();
        callbackInformation.setDialNo(collectingMoneyBalance.getGoodsbillMaster().getSendGoodsCustomerTel());//拨出号码	DialNO
        callbackInformation.setType("货款");//类别	Type
        callbackInformation.setContent("您的验证码"+code+"，该验证码5分钟内有效，请勿泄漏于他人！");//内容	Content
        callbackInformation.setWriteTime(new Date());//填写时间	WriteTime
        callbackInformation.setWriter("财务员");//填写人	Writer
        callbackInformation.setFinallyDialTime(new Date());// 最后拨出时间	FinallyDialTime
        callbackInformation.setSuccess(1);//成功	Success
        //锁定	Locked
        callbackInformation.setBillId(collectingMoneyBalance.getGoodsBillCode());// 货运单编号 单据号	BillID
        callbackInformation.setBillType("货运单");//单据类型	BillType

        // 修改代收表状态
        int coll = collectionCallBackMapper.updateFlagByCmsid(cmsid);
        if(coll==0){
            throw new RuntimeException("数据修改失败，请重新发送");
        }
        // 添加信息到回告表
        int call = callbackInformationMapper.insertSelective(callbackInformation);
        if(call==0){
            throw new RuntimeException("数据修改失败，请重新发送");
        }
    }

    @Override
    public GridResult<CallbackInformation> selectCallbackHistoryByPage(GridRequest gridRequest, CallbackInformation callbackInformation, String startTime, String endTime) {
        // 获取当前页和页大小
        Integer currentPage = gridRequest.getPage();
        Integer pageSize = gridRequest.getLimit();

        // 判断是否有排序,有则生成符合pagehelper的排序字符串
        String sidx = gridRequest.getSidx(); // 排序参数
        String sord = gridRequest.getSord(); // 排序规则

        String orderBy = "";
        // pagehelper静态设置页属性方法，它会拦截下面的第一个查询！第二个无效。
        if(checkOrderBy(sidx, sord)){
            sidx = upperCharToUnderLine(sidx);
            orderBy = sidx+" "+sord;

            PageHelper.startPage(currentPage, pageSize, orderBy);
        }else{
            // 设置当前页和页大小
            PageHelper.startPage(currentPage, pageSize);
        }

        // 查询结果（传入排序）
        List<CallbackInformation> result = callbackInformationMapper.selectCallbackHistory(callbackInformation, startTime, endTime);
        // 利用当前页和页大小配置pageinfo
        PageInfo<CallbackInformation> pageList = new PageInfo<>(result);
        // 新建一个封装类对象，设置参数，传入查询得到的数据
        GridResult<CallbackInformation> grid = new GridResult<>();

        // 存入查询数据
        grid.setData(result);
        // 存入总条数
        grid.setCount(pageList.getTotal());

        return grid;
    }

    @Override
    public void removeHistory(Integer cbiid) {
        int result = callbackInformationMapper.deleteHistory(cbiid);
        if(result==0){
            throw new RuntimeException("删除失败,未找到对应数据，请刷新页面");
        }
    }


    /*--------------------------------工具类------------------------------*/

    /**
     * @description: 判断排序字段和排序规则字符串是否非空
     * @param sidx 排序字段
     * @param sord 排序规则
     * @return: true则非空
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    private boolean checkOrderBy(String sidx,String sord){
        if(sidx != null && sord != null
                && sidx.trim().length() > 0
                && sord.trim().length() > 0){
            return true;
        }
        return false;
    }

    /**
     * @description: 大写转换为下划线+小写
     * @param param 需要转换的字符串
     * @return: 返回转换后的字符串
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    public static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
//            System.out.println(builder.toString());
//            System.out.println("mc.start():" + mc.start() + ", i: " + i);
//            System.out.println("mc.end():" + mc.start() + ", i: " + i);
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }


}
